package grow_task

import (
	"go_server/game_server/constants"
	"go_server/game_server/dao/task_info_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"gorm.io/datatypes"
)

func (s *GrowTaskService) S2C_UpdateGrowTask(conn ziface.IConnection, roleId int64, taskType int32, taskEvent int32, parms map[string]int32) pb.ErrorCodeManager {
	zlog.Infof("成长或支线任务事件接收处理,taskType=%d,taskEvent=%d,parms=%v", taskType, taskEvent, parms)

	id := parms["id"]     // 例如：建筑id或者关卡id,可传0
	num := parms["value"] // 达成的数值

	// 获取成长、支线任务配置列表
	baseTaskList := config_manager.GetStcTableTask_SheetTaskListByTwoType(constants.GROW_TASK, constants.BRANCH_TASK)
	if len(baseTaskList) == 0 {
		zlog.Errorf("baseTaskList 成长或支线任务配置不存在,taskType=%d,taskEvent=%d", taskType, taskEvent)
		return pb.ErrorCodeManager_GROW_BRANCH_TASK_UNFIND
	}

	fields := []string{"grow_task_id", "grow_task", "branch_task"} // 需要查询或者修改的字段
	row := task_info_dao.GetTaskInfoByRoleId(roleId, fields)

	var growTaskId int32                          // 当日活跃度
	growTaskProgress := make(map[int32][]int32)   // 成长任务进度
	branchTaskProgress := make(map[int32][]int32) // 支线任务进度

	if row != nil {
		growTaskId = row.GrowTaskId

		if row.GrowTask.Data() != nil {
			growTaskProgress = row.GrowTask.Data()
		}

		if row.BranchTask.Data() != nil {
			branchTaskProgress = row.BranchTask.Data()
		}
	}

	if growTaskId <= 0 {
		growTaskId = firstGrowTaskId
	}

	eventSet := util.NewSet[int32]()
	eventSet.AddValue(constants.FixedValueEvents)

	var isFixedValue bool // 是否是固定值判断
	if eventSet.Contains(taskEvent) {
		isFixedValue = true
	} else {
		isFixedValue = false
	}

	hasUpdate := false        // 是否有进度、状态更新
	hasChapterUpdate := false // 当前正在进行的章节是否有任务进度、状态更新

	// 遍历主线任务-当前事件下的所有任务
	for taskId, taskVal := range baseTaskList {
		if len(taskVal.Value) <= 0 {
			continue
		}

		var requiredLimit int32

		if len(taskVal.Value) >= 2 {
			requiredId := taskVal.Value[0]
			requiredLimit = taskVal.Value[1]
			if requiredId != id {
				continue
			}
		} else {
			requiredLimit = taskVal.Value[0]
		}

		if taskVal.Type == constants.GROW_TASK {
			taskProgress, exists := growTaskProgress[taskId]

			if exists {
				if taskProgress[2] >= 1 { // 已完成或者已领取,不做任务处理
					continue
				}

				var newProgress int32
				if isFixedValue { // 如果是固定值判断
					newProgress = num // 最新等级、星级
				} else {
					newProgress = taskProgress[1] + num // 最新进度
				}

				if newProgress >= requiredLimit {
					newProgress = requiredLimit

					growTaskProgress[taskId][1] = newProgress // 更新进度
					growTaskProgress[taskId][2] = 1           // 更新任务状态
				} else {
					if isFixedValue { // 如果是固定值判断
						if newProgress > taskProgress[1] {
							growTaskProgress[taskId][1] = newProgress // 更新进度
						}
					} else {
						growTaskProgress[taskId][1] = newProgress // 更新进度
					}
				}
			} else {
				if num >= requiredLimit {
					growTaskProgress[taskId] = []int32{taskId, requiredLimit, 1} // 保存新任务进度、状态
				} else {
					growTaskProgress[taskId] = []int32{taskId, num, 0} // 保存新任务进度
				}
			}

			// 如果当前正在进行的成长任务有进度更新，则推送下行
			if taskId == growTaskId {
				hasChapterUpdate = true
			}
		} else {
			taskProgress, exists := branchTaskProgress[taskId]

			if exists {
				if taskProgress[2] >= 1 { // 已完成或者已领取,不做任务处理
					continue
				}

				var newProgress int32
				if isFixedValue { // 如果是固定值判断
					newProgress = num // 最新等级、星级
				} else {
					newProgress = taskProgress[1] + num // 最新进度
				}

				if newProgress >= requiredLimit {
					newProgress = requiredLimit

					branchTaskProgress[taskId][1] = newProgress // 更新进度
					branchTaskProgress[taskId][2] = 1           // 更新任务状态
				} else {
					if isFixedValue { // 如果是固定值判断
						if newProgress > taskProgress[1] {
							branchTaskProgress[taskId][1] = newProgress // 更新进度
						}
					} else {
						branchTaskProgress[taskId][1] = newProgress // 更新进度
					}
				}
			} else {
				if num >= requiredLimit {
					branchTaskProgress[taskId] = []int32{taskId, requiredLimit, 1} // 保存新任务进度、状态
				} else {
					branchTaskProgress[taskId] = []int32{taskId, num, 0} // 保存新任务进度
				}
			}

			// 如果当前任务没有前置任务,或者前置任务已完成，则推送下行
			if taskVal.PrereQuisites != nil {
				preTaskId := taskVal.PrereQuisites[0] // 前置任务ID

				preBranchTaskInfo, flag := branchTaskProgress[preTaskId]
				if flag && preBranchTaskInfo[2] == 2 {
					hasChapterUpdate = true // 前置任务已完成
				}
			} else {
				hasChapterUpdate = true // 没有前置任务
			}
		}

		hasUpdate = true // 有任务进度、状态更新
	}

	if hasUpdate {
		// 修改任务状态
		taskInfo := task_info_dao.TaskInfo{
			RoleId:     roleId,
			GrowTaskId: growTaskId,
			GrowTask:   datatypes.NewJSONType(growTaskProgress),
			BranchTask: datatypes.NewJSONType(branchTaskProgress),
		}

		task_info_dao.UpdateTaskInfo(&taskInfo, fields) // 修改任务状态

		if hasChapterUpdate {
			msgS2C := ServiceObj.GetGrowTaskList.GetGrowTaskListApiS2C(roleId)
			conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetGrowTaskList), msgS2C)
		}
	}

	return pb.ErrorCodeManager_SUCCESS
}
